from flask import Flask, request
import json
from flask import jsonify

from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

logs = []

from json import JSONEncoder
from sqlalchemy.ext.declarative import declarative_base


class MyEncoder(JSONEncoder):
    def default(self, o):
        return o.__dict__


app.config['SECRET_KEY'] = 'Fianna'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:huhan3@localhost:3306/wifi'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)

def save_message(s):
    rm = RawMessage(message=s)
    db.session.add(rm)
    db.session.commit()


class RawMessage(db.Model):
    __tablename__ = 'raw_message'
    id = db.Column(db.Integer, primary_key=True)
    message = db.Column(db.Text, nullable=False)

    def __repr__(self):
        return '<RawMessage %r>' % self.message

    def to_dict(self):
        return {c.name: getattr(self, c.name, None) for c in self.__table__.columns}


@app.route('/', methods=['GET'])
def get():
    ms = RawMessage.query.limit(50).all()
    print(ms)
    s = json.dumps([r.to_dict() for r in ms])
    print(s)
    return s


@app.route('/', methods=['POST'])
def post():
    s = json.dumps(request.form)
    print(s)
    save_message(s)
    return request.form['device_id']

    json_data = request.get_json(force=True)
    # logs.append(json_data)
    pass
    # parser = reqparse.RequestParser()
    # logs.append(request.form['data'])


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
